<template>
  <sv-page>
    <sv-nav-bar :title="pageTitle" home-icon=""></sv-nav-bar>
    <view class="exam">
      <view class="exam-container">
        <sv-exam type="practice" :data="examData" :showCard="false"
          @changePaper="changePaper" @quit="onQuit"></sv-exam>
      </view>
    </view>
  </sv-page>
</template>

<script setup>
import { computed, ref, getCurrentInstance, nextTick } from 'vue'
import { onLoad, onUnload } from '@dcloudio/uni-app'
import { useSysStore } from '@/store/sys'

const { proxy } = getCurrentInstance();

const sysConfig = useSysStore().getConfig()
const navbarHeight = computed(() => {
  return sysConfig.navbarHeight + 'px'
})

const pageTitle = ref('')

// 题目列表
const examData = ref([])

onLoad(() => {
  // 通信通道传值 - 只监听一次
  const eventChannel = proxy.getOpenerEventChannel()
  eventChannel.once('e-transmit-exams', (res) => {
    pageTitle.value = res.title
    examData.value = res.data
    nextTick(() => {
      uni.$emit('sv-exam-start', res.index)
    })
  })

  examWatcher()
})

function examWatcher() {
  /**
   * 监听题目提交
   * @param e 题目记录: 可根据返回的题目记录，自定义选择存入做题记录或错题本
   */
  uni.$on('e-exam-paper-item-submit', async (e) => {
    console.log('==== 监听题目提交 e-exam-paper-item-submit :', e)
  })
  /**
   * 监听纠错反馈
   * @param e 纠错反馈的题目
   */
  uni.$on('e-exam-paper-item-feedback', (e) => {
    console.log('==== 监听纠错反馈 e-exam-paper-item-feedback :', e)
    uni.navigateTo({
      url: '/pages/mine/feedback/feedback',
      success(res) {
        res.eventChannel.emit('e-transmit-feedback', e)
      }
    })
  })
}

/**
 * 切换题目
 * @param {Object} e 当前题目
 */
function changePaper(e) {
  console.log('==== 切换题目 :', e)
}

/**
 * 退出考试
 * @param {Object} e 做题记录，可缓存或上传云端，用作下一次打开后继续进度
 */
function onQuit(e) {
  console.log('==== 退出考试 :', e)
}

onUnload(() => {
  // 移除事件监听
  uni.$off('e-exam-paper-item-submit')
  uni.$off('e-exam-paper-item-feedback')
})
</script>

<style lang="scss">
.exam {
  width: 100%;
  height: calc(var(--main-height-notab) - v-bind(navbarHeight));

  .exam-container {
    height: inherit;

    @include useTheme {
      background-color: getTheme('sv-background-color');
      color: getTheme('sv-text-color');
    }
  }
}
</style>